import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getStorage, setStorage } from '@/stores/storage'

export const usePlanStore = defineStore('plan', () => {
  // ==================== 状态定义 ====================
  const folders = ref(['默认文件夹']) // 文件夹列表
  const activeFolder = ref('默认文件夹') // 当前选中文件夹
  const plans = ref({
    '默认文件夹': [] // 结构: { folder: [ {id, title, content, subTasks, completed, ...} ] }
  })

  // ==================== 数据初始化 ====================
  const initFromStorage = async () => {
    const saved = await getStorage('planData')
    if (saved) {
      folders.value = saved.folders || folders.value
      activeFolder.value = saved.activeFolder || activeFolder.value
      plans.value = saved.plans || plans.value
    }
  }

  // ==================== 计算属性 ====================
  const currentPlans = computed(() => {
    return plans.value[activeFolder.value] || []
  })

  const activeFolderPendingCount = computed(() => {
    return currentPlans.value.filter(p => !p.completed).length
  })

  // ==================== 文件夹操作方法 ====================
  const addFolder = async (folderName) => {
    if (!folderName || folders.value.includes(folderName)) return false
    
    folders.value.push(folderName)
    plans.value[folderName] = []
    activeFolder.value = folderName
    await saveToStorage()
    return true
  }

  // 重命名文件夹（新增方法）
  const renameFolder = async (oldName, newName) => {
    if (!oldName || !newName || 
        oldName === '默认文件夹' || 
        folders.value.includes(newName)) {
      return false
    }

    const folderIndex = folders.value.indexOf(oldName)
    if (folderIndex === -1) return false

    // 更新文件夹列表
    folders.value[folderIndex] = newName

    // 更新计划数据
    if (plans.value[oldName]) {
      plans.value[newName] = plans.value[oldName]
      delete plans.value[oldName]
    }

    // 更新当前活动文件夹
    if (activeFolder.value === oldName) {
      activeFolder.value = newName
    }

    await saveToStorage()
    return true
  }

  // 删除文件夹（增强健壮性）
  const deleteFolder = async (folderName) => {
    try {
      if (folderName === '默认文件夹' || 
          folders.value.length <= 1 || 
          !folders.value.includes(folderName)) {
        return false
      }

      const index = folders.value.indexOf(folderName)
      if (index === -1) return false

      // 检查是否有未完成的计划
      const hasPendingPlans = plans.value[folderName]?.some(p => !p.completed)
      if (hasPendingPlans) {
        uni.showToast({ 
          title: '请先完成或删除所有计划', 
          icon: 'none',
          duration: 2000
        })
        return false
      }

      // 执行删除
      folders.value.splice(index, 1)
      delete plans.value[folderName]

      // 更新当前活动文件夹
      if (activeFolder.value === folderName) {
        activeFolder.value = folders.value[Math.max(0, index - 1)]
      }

      await saveToStorage()
      return true
    } catch (error) {
      console.error('删除文件夹失败:', error)
      return false
    }
  }

  const switchFolder = async (folderName) => {
    if (folders.value.includes(folderName)) {
      activeFolder.value = folderName
      await saveToStorage()
      return true
    }
    return false
  }

  // ==================== 计划操作方法 ====================
  const addPlan = async (plan) => {
    if (!plans.value[activeFolder.value]) return false
    
    const newPlan = {
      id: Date.now().toString(),
      title: plan.title || '未命名计划',
      content: plan.content || '',
      subTasks: plan.subTasks || [],
      completed: false,
      createdAt: new Date().toISOString(),
      priority: plan.priority || 'medium'
    }
    
    plans.value[activeFolder.value].unshift(newPlan)
    await saveToStorage()
    return newPlan.id
  }

  const updatePlan = async (planId, updates) => {
    const folderPlans = plans.value[activeFolder.value]
    const index = folderPlans.findIndex(p => p.id === planId)
    
    if (index !== -1) {
      folderPlans[index] = { ...folderPlans[index], ...updates }
      await saveToStorage()
      return true
    }
    return false
  }

  const deletePlan = async (planId) => {
    const folderPlans = plans.value[activeFolder.value]
    const index = folderPlans.findIndex(p => p.id === planId)
    
    if (index !== -1) {
      folderPlans.splice(index, 1)
      await saveToStorage()
      return true
    }
    return false
  }

  const togglePlanComplete = async (planId) => {
    const folderPlans = plans.value[activeFolder.value]
    const index = folderPlans.findIndex(p => p.id === planId)
    
    if (index !== -1) {
      folderPlans[index].completed = !folderPlans[index].completed
      await saveToStorage()
      return true
    }
    return false
  }

  // ==================== 子任务操作 ====================
  const addSubTask = async (planId, taskText) => {
    const folderPlans = plans.value[activeFolder.value]
    const index = folderPlans.findIndex(p => p.id === planId)
    
    if (index !== -1) {
      if (!folderPlans[index].subTasks) {
        folderPlans[index].subTasks = []
      }
      folderPlans[index].subTasks.push({
        id: Date.now().toString(),
        text: taskText,
        completed: false
      })
      await saveToStorage()
      return true
    }
    return false
  }

  const toggleSubTaskComplete = async (planId, taskId) => {
    const folderPlans = plans.value[activeFolder.value]
    const planIndex = folderPlans.findIndex(p => p.id === planId)
    
    if (planIndex !== -1 && folderPlans[planIndex].subTasks) {
      const taskIndex = folderPlans[planIndex].subTasks.findIndex(t => t.id === taskId)
      if (taskIndex !== -1) {
        folderPlans[planIndex].subTasks[taskIndex].completed = 
          !folderPlans[planIndex].subTasks[taskIndex].completed
        await saveToStorage()
        return true
      }
    }
    return false
  }

  // ==================== 持久化方法 ====================
  const saveToStorage = async () => {
    try {
      return await setStorage('planData', {
        folders: folders.value,
        activeFolder: activeFolder.value,
        plans: plans.value
      })
    } catch (error) {
      console.error('保存数据失败:', error)
      return false
    }
  }

  // ==================== 导出 ====================
  return {
    folders,
    activeFolder,
    plans,
    currentPlans,
    activeFolderPendingCount,
    initFromStorage,
    addFolder,
    renameFolder, // 新增导出
    deleteFolder,
    switchFolder,
    addPlan,
    updatePlan,
    deletePlan,
    togglePlanComplete,
    addSubTask,
    toggleSubTaskComplete,
    saveToStorage
  }
})